//
//  FoodSortVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/11/20.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "FoodSortVC.h"
#import "XRDragTableView.h"
#import "SortCell.h"

@interface FoodSortVC ()<UITableViewDelegate,UITableViewDataSource>{
    NSMutableArray *_operationDataArray;//操作数据
    NSMutableArray *_primitiveArray;//保存原始数据
}

@property(nonatomic,strong)XRDragTableView *tableView;
@property(nonatomic,strong)NSMutableArray *sortArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttomConstraint;
@property (weak, nonatomic) IBOutlet UIButton *allSelectBtn;//全选

@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;//删除
@property (weak, nonatomic) IBOutlet UIButton *shelvesBtn;//上架
@property (weak, nonatomic) IBOutlet UIButton *theShelvesBtn;//下架

@end

@implementation FoodSortVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitle:_foodTitle titleColor:[UIColor blackColor] font:font17];
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];
    [self.view addSubview:self.tableView];
    
    if(SCREEN_H == 812) self.buttomConstraint.constant = 34;
    
    [self getCategorycontent];
    
    UIButton *savebtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [savebtn setTitle:@"保存" forState:0];
    [savebtn setTitleColor:kGrayColor forState:0];
    [savebtn addTarget:self action:@selector(saveFoodSort) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:savebtn];
  
    __weak typeof (self)weakself = self;
    [self.backBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        if([self dataContrast]){
            [weakself.navigationController popViewControllerAnimated:YES];
        }else{
            [weakself backAction];
        }
    }];
}


//此数据组成只适应此界面

- (NSMutableArray *)getNewDataArray:(NSArray *)array{
    NSMutableArray *arr1 = @[].mutableCopy;
    for (int i=0; i<array.count; i++) {
         NSMutableDictionary *dic =  ((NSDictionary *)array[i]).mutableCopy;
        [dic setObject:@"0" forKey:@"is_select"];
        [arr1 addObject:dic];
    }
    return arr1;
}


- (void)getCategorycontent{
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/cateGoodsList" isactive:NO parameter:@{@"category_id":_model.categoryID} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
        NSMutableArray *newresponseObj = [weakself getNewDataArray:responseObj];
        NSMutableArray *arr = @[].mutableCopy;
        [newresponseObj enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CategoryContentModel *model = [CategoryContentModel yy_modelWithJSON:obj];
            [arr addObject:model];
        }];
        _sortArray = arr;
        _tableView.dataArray = _sortArray;
        _primitiveArray = [NSMutableArray arrayWithArray:_sortArray];
        _allSelectBtn.selected = NO;
        [_tableView reloadData];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];
}


#pragma  mark ========懒加载========

- (XRDragTableView *)tableView{
    if(_tableView==nil){
        _tableView = [[XRDragTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-50-NavigationHeight-TableSafe) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.scrollSpeed = 10;
        [_tableView registerClass:[SortCell class] forCellReuseIdentifier:@"SortCell"];
    }
    return _tableView;
}

- (NSMutableArray *)sortArray{
    if(_sortArray == nil){
        _sortArray = @[].mutableCopy;
    }
    return _sortArray;
}

//置顶的数据源处理方法
- (void)stickAction:(UIButton *)sender{
    NSString *str = self.sortArray[sender.tag];
    [self.sortArray removeObjectAtIndex:sender.tag];
    [self.sortArray insertObject:str atIndex:0];
    [self.tableView reloadData];
    
}

#pragma  mark ========全选 删除 上架 下架 保存========

- (IBAction)selectAction:(UIButton*)sender {
    _allSelectBtn.selected = !sender.selected;
    for(int i=0;i<_sortArray.count;i++){
        CategoryContentModel *model = _sortArray[i];
        model.is_select = _allSelectBtn.selected?@"1":@"0";
        _sortArray[i] = model;
    }
    
    [_tableView reloadData];
    
}

- (IBAction)deleteAction:(UIButton*)sender {
    NSString *goodsID = @"";
    for (CategoryContentModel*mode in _sortArray) {
        if([mode.is_select isEqualToString:@"1"]){
            goodsID = [NSString stringWithFormat:@"%@,%@",goodsID,mode.goodID];
        }
    }
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/goodsDel" isactive:NO parameter:@{@"goods_ids":goodsID} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        
        [AlertUtils showToastWithMessage:@"删除成功" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        [weakself getCategorycontent];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];
}
- (IBAction)shelvesAction:(UIButton*)sender {
    [self shopOperateAction:YES];
}

- (IBAction)theShelvesAction:(UIButton*)sender {
    [self shopOperateAction:NO];
}

/**
 上下架

 @param state YES 上架 NO下架
 */
- (void)shopOperateAction:(BOOL)state{
    NSString *is_on_sale = state?@"1":@"0";
    NSString *goodsID = @"";
   
    for (CategoryContentModel*mode in _sortArray) {
        if([mode.is_select isEqualToString:@"1"]){
            goodsID = [NSString stringWithFormat:@"%@,%@",goodsID,mode.goodID];
        }
    }
    
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/goodsSetSale" isactive:NO parameter:@{@"goods_ids":goodsID,@"is_on_sale":is_on_sale} successBlock:^(PPHttpRequest *request, NSArray* responseObj) {
        NSString *message = state?@"上架成功":@"下架成功";
        [AlertUtils showToastWithMessage:message inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        [weakself getCategorycontent];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];

}

- (void)backAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否保存修改的信息" preferredStyle:UIAlertControllerStyleAlert];
    __weak typeof (self)weakSelf = self;
    [alertController addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf saveFoodSort];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (BOOL)dataContrast{
    NSString *str = [_primitiveArray componentsJoinedByString:@","];
    NSString *str1 = [ToolClass md5:str];
    NSString *ptr = [_sortArray componentsJoinedByString:@","];
    NSString *ptr1 = [ToolClass md5:ptr];
    return [str1 isEqualToString:ptr1];
}

//保存排序
-(void)saveFoodSort{
  
    if([self dataContrast]){
        [AlertUtils showToastWithMessage:@"您没有进行操作，不需要保存！" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    NSMutableArray *newSort = @[].mutableCopy;
    for(int i=0;i<_sortArray.count;i++){
        CategoryContentModel *model = _sortArray[i];
        NSData *data = [model yy_modelToJSONData];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSMutableDictionary *newdic = dic.mutableCopy;
        newdic[@"sort"] = [NSString stringWithFormat:@"%ld",_sortArray.count-i];
        [newSort addObject:newdic];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newSort options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
      __weak typeof (self)weakSelf = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Goods/goodsSort" isactive:YES parameter:@{@"data":jsonStr} successBlock:^(PPHttpRequest *request,id responseObj) {
        
        [AlertUtils showToastWithMessage:@"保存成功" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
        //_primitiveArray = [NSMutableArray arrayWithArray:_sortArray];
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];

}

#pragma  mark ========UITableViewDelegate DATASOURCE========

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sortArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SortCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SortCell" forIndexPath:indexPath];
    if(indexPath.row == 0){
        cell.stickBtn.hidden = YES;
    }else{
        cell.stickBtn.hidden = NO;
    }
    cell.categoryContentModel = _sortArray[indexPath.row];
    [cell.dragBtn setBackgroundImage:[UIImage new] forState:UIControlStateNormal];
    [cell.dragBtn  addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self.tableView action:@selector(moveRow:)]];
    
    cell.stickBtn.tag = indexPath.row;
    [cell.stickBtn addTarget:self action:@selector(stickAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.selectBtn.tag = indexPath.row;
    [cell.selectBtn addTarget:self action:@selector(selecetRowAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CategoryContentModel *model = _sortArray[indexPath.row];
    model.is_select = [model.is_select isEqualToString:@"0"]?@"1":@"0";
    _sortArray[indexPath.row] = model;
    //[_tableView reloadData];
    BOOL isallselect = YES;
    for (CategoryContentModel*mode in _sortArray) {
        if([mode.is_select isEqualToString:@"0"]){
             isallselect = NO;
        }
    }
    _allSelectBtn.selected = isallselect;
    
    //[_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [_tableView reloadData];
}

#pragma  mark ========选中效果========
- (void)selecetRowAction:(UIButton *)btn{
    CategoryContentModel *model = _sortArray[btn.tag];
    model.is_select = [model.is_select isEqualToString:@"0"]?@"1":@"0";
    _sortArray[btn.tag] = model;
    
    BOOL isallselect = YES;
    for (CategoryContentModel*mode in _sortArray) {
        if([mode.is_select isEqualToString:@"0"]){
            isallselect = NO;
        }
    }
    _allSelectBtn.selected = isallselect;
    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
}

@end
